#include "scripteditorwidget.h"

ScriptEditorWidget::ScriptEditorWidget(QWidget *parent) :
    QWidget(parent)
{
    QVBoxLayout *mainLayout = new QVBoxLayout;
    setLayout(mainLayout);

    m_toolBar = new QToolBar("Tools");
    mainLayout->addWidget(m_toolBar);

    m_docTabs = new QTabWidget;
    m_docTabs->setTabsClosable(true);
    mainLayout->addWidget(m_docTabs);

    createActions();

    connect(m_docTabs, SIGNAL(tabCloseRequested(int)), this, SLOT(closeEditor(int)));

    completer = new QCompleter(this);
    completer->setModel(modelFromFile(":/completer/wordslist.txt"));
    completer->setModelSorting(QCompleter::CaseSensitivelySortedModel);
    completer->setCaseSensitivity(Qt::CaseSensitive);
    completer->setWrapAround(false);
    //completer->popup()->setStyleSheet("background-color: yellow");


}

void ScriptEditorWidget::createActions(){
    m_newEditorAction = new QAction("New",this);
    m_newEditorAction->setIcon(QIcon(":/images/document.png"));
    connect(m_newEditorAction,SIGNAL(triggered()),this,SLOT(addEditor()));
    m_toolBar->addAction(m_newEditorAction);

    m_saveEditorAction = new QAction("Save",this);
    m_saveEditorAction->setIcon(QIcon(":/images/save.png"));
    m_saveEditorAction->setShortcut(QKeySequence("Ctrl+S"));
    connect(m_saveEditorAction,SIGNAL(triggered()),this,SLOT(saveCurrentEditor()));
    m_toolBar->addAction(m_saveEditorAction);
}

void ScriptEditorWidget::addEditor(const QString &fileName){

    for(int i = 0; i < m_editors.size(); i++){
        if(m_editors[i]->getCurrentFile()==fileName){
            m_docTabs->setCurrentIndex(i);
            return;
        }
    }

    ScriptEditor *editor = new ScriptEditor;
    editor->loadScript(fileName);

    m_docTabs->addTab(editor, fileName.split("/").last());
    m_editors.append(editor);
    connect(editor,SIGNAL(dirtyChanged(bool)),this,SLOT(setDirtyEditor(bool)));
    m_docTabs->setCurrentIndex(m_docTabs->count()-1);


    editor->setCompleter(completer);
}

void ScriptEditorWidget::addEditor(){
    QString fileName = QFileDialog::getSaveFileName(this,tr("Create new file"),
                                                    QString(),tr("Python Script (*.py)"));

    if(fileName.isEmpty())
        return;

    // Falta comprovar que no estigues creant sobre
    // algo que tens obert en el editor.

    ScriptEditor *editor = new ScriptEditor;
    editor->setCurrentFile(fileName);
    if(!editor->saveScript()){
        QMessageBox::warning(this,"ERROR", "Couldn't create file.");
        delete editor;
        return;
    }


    editor->setCompleter(completer);
    m_docTabs->addTab(editor, fileName.split("/").last());
    m_editors.append(editor);
    connect(editor,SIGNAL(dirtyChanged(bool)),this,SLOT(setDirtyEditor(bool)));
    m_docTabs->setCurrentIndex(m_docTabs->count()-1);

    emit scriptAdded(fileName);
}


void ScriptEditorWidget::saveCurrentEditor(){
    if(m_docTabs->count())
        m_editors[m_docTabs->currentIndex()]->saveScript();
}


void ScriptEditorWidget::clean(){
    m_docTabs->clear();

    for(int i = 0; i < m_editors.size(); i++){
        m_editors[i]->disconnect();
        delete m_editors[i];
    }

    m_editors.clear();

}

void ScriptEditorWidget::setDirtyEditor(bool value){
    int index = m_docTabs->currentIndex();

    QString current = m_docTabs->tabText(index);
    if(value){
        m_docTabs->setTabText(index, QString("* ")+current);
    }else{
        m_docTabs->setTabText(index,current.right(current.length()-2));
    }
}

void ScriptEditorWidget::closeEditor(int index){
    if(m_editors[index]->isDirty()){
        int res = QMessageBox::question(this, "Closing script","This file has unsaved changes.\nClose anyway?", QMessageBox::Ok, QMessageBox::Cancel);
        if(res == QMessageBox::Cancel)
            return;
    }
    m_docTabs->removeTab(index);
    m_editors[index]->disconnect();
    delete m_editors[index];
    m_editors.remove(index);
}

QAbstractItemModel *ScriptEditorWidget::modelFromFile(const QString& fileName)
{
    QFile file(fileName);
    if (!file.open(QFile::ReadOnly))
        return new QStringListModel(completer);


    QStringList words;

    while (!file.atEnd()) {
        QByteArray line = file.readLine();
        if (!line.isEmpty())
            words << line.trimmed();
    }

    words.sort();
    return new QStringListModel(words, completer);
}
